package com.cj.stock.service.impl;

import com.cj.stock.service.SpikeService;
import lombok.extern.slf4j.Slf4j;
import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

/**
 * @Author cheng jun
 * @Description:
 * @Date 2021/8/8 16:56
 */
@Service("level3SpikeServiceImpl")
@Slf4j
public class Level3SpikeServiceImpl implements SpikeService {

    @Autowired
    private Redisson redisson;

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    @Async("taskExecutor")
    public boolean spikeStock() {
        // redisson的锁，本质也是分布式锁
        String distributedLock = "distributedLock";
        RLock redissonLock = redisson.getLock(distributedLock);
        try {
            String inStock = "inStock";
            redissonLock.lock();
            // 从redis拿库存
            int stock = Integer.parseInt(String.valueOf(redisTemplate.opsForValue().get(inStock)));
            if (stock > 0) {
                // 重新设置库存大小
                int realStock = stock - 1;
                redisTemplate.opsForValue().set("inStock", realStock);
                log.info("减库存成功,剩余库存数:" + realStock);
            } else {
                log.info("库存不够");
            }
        } catch (Exception e) {
            log.error(e.getMessage());
            throw e;
        } finally {
            // 释放锁
            redissonLock.unlock();
        }

        return true;
    }
}
